<?php

namespace app\webapi\controller;

use think\facade\Db;
use think\facade\Request;

class ApiOrder extends ApiBaseController
{
    public $user_info = null;

    public function __construct()
    {
        $this->user_info = $this->checkToken();
        if (!preg_match('/^\d+$/', $this->user_info['id'])) {
            $this->result_error('用户id出错');
        }
    }

    /** 货架商品  获取支付参数 */
    public function purchasePrepare()
    {
        $user_info = $this->user_info;
        $order_id = (int)Request::param('order_id');
        $order_no = Request::param('order_no');
        $address_info = Request::param('address_info');
        if (!($order_id > 0)) {
            $this->result_error('订单id错误');
        }
        if (empty($order_no)) {
            $this->result_error('订单号错误');
        }
        $order_info = Db::query(
            'SELECT * FROM sy_user_order_shelves WHERE id=? AND order_no=? AND state=1 AND pay_state=0',
            [$order_id, $order_no]
        );
        if (empty($order_info)) {
            $this->result_error('订单信息核对失败');
        }
        if (empty($address_info)) {
            $address_info = json_encode($address_info, JSON_UNESCAPED_UNICODE);
//            UPDATE user_order_shelves SET address_info=? WHERE order_id=?
            Db::name('user_order_shelves')->where('id', $order_id)->update([
                'address_info' => $address_info
            ]);
        }
        $order_info = $order_info[0];
        // 订单显示名称
        $gname = '商城商品';
        $allGoods = json_decode($order_info['goods_info'], true);
        if (!empty($allGoods)) {
            $gname = implode(',', array_column($allGoods, 'name'));
            if (strlen($gname) == 0) {
                $gname = '商城商品';
            } elseif (strlen($gname) > 127) {
                $gname = substr($gname, 0, 120) . '...';
            }
        }
        $payprepare = ApiWxPay::getPay(
            $gname,
            $order_info['order_no'],
            $order_info['real_price'],
            $user_info['open_id'],
            $order_info['uid'],
            'home'
        );
        if ($payprepare['status'] = 200) {
            $this->result_ok('ok', $payprepare);
        } else {
            $this->result_error('获取支付信息失败', $payprepare);
        }

    }

    /**
     * 货架商品  获取支付参数
     */
    public function alipayPurchasePrepare()
    {
        $user_info = $this->user_info;
        $order_id = (int)Request::param('order_id');
        $order_no = Request::param('order_no');
        $address_info = Request::param('address_info');
        if (!($order_id > 0)) {
            $this->result_error('订单id错误');
        }
        if (empty($order_no)) {
            $this->result_error('订单号错误');
        }
        $order_info = Db::query(
            'SELECT * FROM sy_user_order_shelves WHERE order_id=? AND order_no=? AND state=1 AND pay_state=0',
            [$order_id, $order_no]
        );
        if (empty($order_info)) {
            $this->result_error('订单信息核对失败');
        }
        if (empty($address_info)) {
            $address_info = json_encode($address_info, JSON_UNESCAPED_UNICODE);
//            UPDATE user_order_shelves SET address_info=? WHERE order_id=?
            Db::name('user_order_shelves')->where('id', $order_id)->update([
                'address_info' => $address_info
            ]);
        }
        $order_info = $order_info[0];
        // 订单显示名称
        $gname = '商城商品';
        $allGoods = json_decode($order_info['goods_info'], true);
        if (!empty($allGoods)) {
            $gname = implode(',', array_column($allGoods, 'name'));
            if (strlen($gname) == 0) {
                $gname = '商城商品';
            } elseif (strlen($gname) > 127) {
                $gname = substr($gname, 0, 120) . '...';
            }
        }
        $payprepare = ApiAliPay::getPay(
            $gname,
            $order_info['order_no'],
            $order_info['real_price'],
            $user_info['open_id'],
            $order_info['uid'],
            'home'
        );
        if ($payprepare['status'] = 200) {
            $this->result_ok('ok', $payprepare);
        } else {
            $this->result_error('获取支付信息失败', $payprepare);
        }
    }

    /**
     * 支付确认
     * 微信支付可用后此方法删除不用，回调中处理这个逻辑
     */
    public function purchaseAck()
    {
        $user_info = $this->user_info;
        $order_id = (int)Request::param('order_id');
        if (!($order_id > 0)) {
            $this->result_error('订单id错误');
        }
        $order_info = Db::query(
            'SELECT * FROM sy_user_order_shelves WHERE order_id=?',
            [$order_id]
        );
        if (count($order_info) < 1) {
            $this->result_error('没有查询到订单' . $order_id);
        }
        $order_info = $order_info[0];
        $list = json_decode($order_info['goods_info'], true);
        // 启动事务
        Db::startTrans();
        try {
            $up_res = [];
            foreach ($list as $v) {
                $up_res[] = Db::name('goods_shelves')
                    ->where('id', $v['id'])
                    ->dec('count')
                    ->update();
            }
//            UPDATE user_order_shelves SET pay_state=1 WHERE order_id=? AND uid=?
            $up_res[] = Db::name('user_order_shelves')
                ->where('id', $order_id)
                ->where('uid', $order_info['uid'])
                ->update(['pay_state' => 1]);
            if (in_array(0, $up_res) || in_array(false, $up_res)) {
                Db::rollback();
                $this->result_error("购买失败!");
            }
            // 提交事务
            Db::commit();
            $this->result_ok("购买成功!");
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->result_error("购买失败!");
        }


    }

    /** 上传支付截图 */
    public function addPayImg()
    {
        $user_info = $this->user_info;
        $order_id = (int)Request::param('order_id');
        $imgurl = Request::param('imgurl');
        if (!($order_id > 0)) {
            $this->result_error('订单id错误');
        }
        if (empty($imgurl)) {
            $this->result_error("支付截图地址错误");
        }
        $in_res = Db::name('user_order_payimg')->insertGetId([
            'uid' => $user_info['id'],
            'order_id' => $order_id,
            'img' => $imgurl,
        ]);
        if ($in_res) {
            $this->result_ok("上传成功!");
        } else {
            $this->result_error("上传失败");
        }
    }

    /** 购物车提交订单【2】 */
    public function submitOrder()
    {
        $user_info = $this->user_info;
        $total_price = Request::param('total_price');
        $list = Request::param('list');
//        var_dump(str_ireplace('"', "\"", $list[0]['img']));die;
        if (!($total_price > 0)) {
            $this->result_error("订单信息错误");
            return;
        }
        if (empty($list)) {
            $this->result_error("商品信息错误");
        }
        $lockObj = [];
        $lockProps = [];
        $checkResult = true;
//        var_dump($list);die;
        foreach ($list as $k => $v) {
            $gid = $v['gid'];
            $ckCount = APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $gid, -$v['count']);
            $lockObj[$gid] = $v['count'];
            $lockProps[] = $gid;
            $list[$k]['img'] = htmlspecialchars_decode($v['img']);
            if ($ckCount < 0) {
                $checkResult = false;
                break;
            }
        }
        if (!$checkResult) {
            foreach ($lockProps as $lv) {
                APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $lv, $lockObj[$lv]);
            }
            $this->result_error("剩余商品数量不足");
        }
        foreach ($list as $lv1) {
            $goodsInfo = APiRedisServer::selected(3)->hGet(self::KEYS['SHELVES_GOODS'] . '0', $lv1['gid']);
            $goodsInfo = json_decode($goodsInfo, true);
            $goodsInfo['count'] = $v['goods_count'] - $v['count'];
            APiRedisServer::selected(3)->HSET(self::KEYS['SHELVES_GOODS'] . '0', $lv1['gid'], json_encode($goodsInfo, JSON_UNESCAPED_UNICODE));
            if ($goodsInfo['cid'] > 0) {
                APiRedisServer::selected(3)->HSET(self::KEYS['SHELVES_GOODS'] . $goodsInfo['cid'], $lv1['gid'], json_encode($goodsInfo, JSON_UNESCAPED_UNICODE));
            }

        }
        $order_id = $this->createShelvesOrder($user_info['id'], $list, $total_price);
        if ($order_id > 0) {
            $this->result_ok("创建订单成功!", $order_id);
        }
        $this->result_error("创建订单失败!");

    }

    /** 首页商品提交订单【2】 */
    public function submitShelvesOrder()
    {
        $user_info = $this->user_info;
        $total_price = (int)Request::param('total_price');
        if (!($total_price > 0)) {
            $this->result_error("订单价格错误");
        }
        $gid = (int)Request::param('gid');
        if (!($gid > 0)) {
            $this->result_error("商品id错误");
        }
        $count = (int)Request::param('count');
        if (!($count > 0)) {
            $this->result_error("商品数量错误");
        }
        $address_info = Request::param('address_info');
        if (!$address_info) {
            $this->result_error("地址信息错误");
        }

        $ckCount = APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $gid, -$count);
//        var_dump($ckCount);
//        if (empty($ckCount)) {
//            $this->result_error("订单确认失败1");
//        }
//        var_dump($ckCount);die;
        if ($ckCount < 0) {
            APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $gid, $count);
            $this->result_error("剩余数量不足，请重新提交", [
                "remain" => $count + $ckCount
            ]);

        }

        $goodsInfo = APiRedisServer::selected(3)->hGet(self::KEYS['SHELVES_GOODS'] . '0', $gid);
        if (empty($goodsInfo)) {
            APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $gid, $count);
            $this->result_error("订单确认失败2");
        } else {
            $goodsInfo = json_decode($goodsInfo, true);
            if ($total_price == $goodsInfo['price'] * $count) {
                $goodsInfo['count'] -= $count;
                APiRedisServer::selected(3)->HSET(self::KEYS['SHELVES_GOODS'] . '0', $gid, json_encode($goodsInfo, JSON_UNESCAPED_UNICODE));
                if ($goodsInfo['cid'] > 0) {
                    APiRedisServer::selected(3)->HSET(self::KEYS['SHELVES_GOODS'] . $goodsInfo['cid'], $gid, json_encode($goodsInfo, JSON_UNESCAPED_UNICODE));
                }
            } else {
                APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $gid, $count);
                $this->result_error("订单确认失败,价格错误");
            }
        }

        $goodsInfo['goods_count'] = $goodsInfo['count'];
        $goodsInfo['count'] = $count;
        $order_id = $this->createShelvesOrder($user_info['id'], [$goodsInfo], $total_price, $address_info);
        if ($order_id > 0) {
            $this->result_ok("创建订单成功!", $order_id);
        } else {
            APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $gid, $count);
            $this->result_error("创建订单失败!");
        }


    }

    /** 取消首页商品订单【2】 */
    public function cancelShelvesOrder()
    {
        $user_info = $this->user_info;
        $order_id = (int)Request::param('order_id');
        if (!($order_id > 0)) {
            $this->result_error("订单id错误");
        }
        $order = Db::query("SELECT * FROM sy_user_order_shelves WHERE id=? AND uid=? AND pay_state=0 AND state=1", [$order_id, $user_info['id']]);

        if (count($order) > 0) {
            $order = $order[0];
            $allgoods = json_decode($order['goods_info'], true);

            foreach ($allgoods as $av) {
                $buy_count = $av['count'];
                $goodsInfo = APiRedisServer::selected(3)->hGet(self::KEYS['SHELVES_GOODS'] . '0', $av['id']);
                if (empty($goodsInfo)) {
                    echo "没找到订单";
                    die;
                } else {
                    $goodsInfo = json_decode($goodsInfo, true);
                    $goodsInfo['count'] += $buy_count;
                    APiRedisServer::selected(3)->HSET(self::KEYS['SHELVES_GOODS'] . '0', $goodsInfo['gid'], json_encode($goodsInfo, JSON_UNESCAPED_UNICODE));
                    if ($goodsInfo['cid'] > 0) {
                        APiRedisServer::selected(3)->HSET(self::KEYS['SHELVES_GOODS'] . $goodsInfo['cid'], $goodsInfo['gid'], json_encode($goodsInfo,JSON_UNESCAPED_UNICODE));
                    }
                    APiRedisServer::selected(3)->HINCRBY(self::KEYS['SHELVES_GOODS_COUNTER'], $goodsInfo['gid'], $buy_count);
                }

            }
            $up_res = Db::name('user_order_shelves')->where('id', $order_id)->update(['state' => -1]);
            if ($up_res) {
                $this->result_ok("取消成功!");

            } else {
                $this->result_error("取消失败!");
            }
        } else {
            $this->result_error("没有找到相关订单或订单状态不匹配");
        }

    }

    /** 货架首页商品查看订单【2】 */
    public function viewOrder()
    {
        $user_info = $this->user_info;
        $order_id = (int)Request::param('order_id');
        if (!($order_id > 0)) {
            $this->result_error("订单id错误");
        }
        $sql_result = Db::name('user_order_shelves')->field('*,id as order_id')->where('id', $order_id)->find();
        if (!empty($sql_result)) {
            $this->result_ok("ok!", $sql_result);
        } else {
            $this->result_error("没有找到相关订单");
        }
    }

    /** 创建抢购商品订单（用户抢购成功） */
    public static function createRushOrder($uid, $goods, $sid, $address_info)
    {
        $timeDtr = date('yymdHis', time());
        $uidStr = str_pad(1, 6, "0", STR_PAD_LEFT);
        $ran = mt_rand(1111, 9999);
        $order_no = "D" . $timeDtr . $uidStr . $ran;
        $sql_result = Db::name('user_order')->insertGetId([
            'order_no' => $order_no,
            'uid' => $uid,
            'gid' => $goods['id'],
            'schedule_id' => $sid,
            'g_price' => $goods['price'],
            'g_count' => 1,
            'saler_id' => $goods['belong'],
            'address_info' => json_encode($address_info, JSON_UNESCAPED_UNICODE),
        ]);
        if ($sql_result > 0) {
            return $sql_result;
        }

        return -1;
    }

    /** 创建货架商品订单（用户首页购买） */
    public static function createShelvesOrder($uid, $list, $total_price, $address_info = '')
    {
        $timeDtr = date('yymdHis', time());
        $uidStr = str_pad(1, 6, "0", STR_PAD_LEFT);
        $ran = mt_rand(0, 9);
        $order_no = "H" . $timeDtr . $uidStr . $ran;
        if ($address_info) {
            $address_info = json_encode($address_info, JSON_UNESCAPED_UNICODE);
        } else {
            $address_info = "";
        }
        $sql_result = Db::name('user_order_shelves')->insertGetId([
            'order_no' => $order_no,
            'uid' => $uid,
            'goods_info' => json_encode($list, JSON_UNESCAPED_UNICODE),
            'price' => $total_price,
            'real_price' => $total_price,
            'address_info' => $address_info,
        ]);
        if ($sql_result > 1) {
            return $sql_result;
        }
        return -1;
    }

    public static $tick = 0;

    /**
     * 创建上架订单
     */
    public static function createPublishOrder($uid, $gid, $newprice, $oldprice, $payprice, $rate, $coupon_id, $relate_order_id)
    {
        $timeDtr = date('yymdHis', time());
        $uidStr = str_pad(1, 6, "0", STR_PAD_LEFT);
        $ran = mt_rand(0, 9);
        self::$tick++;
        $order_no = "P" . $timeDtr . $uidStr . $ran . str_pad((self::$tick % 1000), 3);

        Db::startTrans();
        try {
            $sql_result = Db::name('user_order_shelves')->insertGetId([
                'order_no' => $order_no,
                'uid' => $uid,
                'gid' => $gid,
                'newprice' => $newprice,
                'oldprice' => $oldprice,
                'payprice' => $payprice,
                'rate' => $rate,
                'coupon_id' => $coupon_id,
                'relate_order_id' => $relate_order_id,
            ]);
            $sql_2 = Db::name('user_coupon')->where('uid', $uid)->where('id', $coupon_id)->update(['state' => -1]);
            if ($sql_result && $sql_2) {
                Db::commit();
                return ['id' => $sql_result, 'order_no' => $order_no];
            }
            Db::rollback();
            return -1;

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return -1;
        }
    }

    /** admin调用的 暂不写 */
    public static function createPublishOrderDiv()
    {

    }
}